import { Body, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entity/user.entity';
import { ApiException } from 'src/exception/api.exception';
import { JWTUtil } from 'src/utils/jwt';
import { EntityManager, Repository, Transaction, TransactionManager } from 'typeorm';

@Injectable()
export class UserService {

    constructor(
        @InjectRepository(User)
        private readonly userRepository: Repository<User>
    ) { }

    @Transaction()
    async login(email: string, @TransactionManager() manager?: EntityManager): Promise<string> {

        let record = await this.userRepository.findOne({
            email: email
        })

        let uid;

        if (!record) {
            const resultSet = await this.userRepository.insert({
                create_time: new Date(),
                email: email,
                update_time: new Date()
            })

            if (!resultSet) {
                throw new ApiException("创建数据异常");
            }

            uid = resultSet.identifiers[0].id
        } else {
            uid = record.id;
        }

        const payload = { uid }
        const token = JWTUtil.generateToken(payload, 60 * 60 * 24 * 7)
        return token;
    }

    async getUserInfo(uid: number): Promise<User> {
        return await this.userRepository.findOne({ id: uid });
    }

    async setUserName(uid: number, name: string): Promise<void> {
        await this.userRepository.update({id:uid},{name:name})
    }
}
